<template>
  <el-dialog
    v-model="visible"
    :title="$t('components.modifyUseAddress')"
    :modal="false"
    top="200px"
    :close-on-click-modal="false"
    class="components-order-addr-update"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="80px"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-alert
        :title="$t('components.consultWithUsers')"
        type="warning"
        show-icon
      />
      <br>
      <el-form-item
        :label="$t('order.addressee')"
        prop="receiver"
        class="itemBottom"
      >
        <el-input
          v-model="dataForm.receiver"
          :placeholder="$t('shop.consigneeName')"
        />
      </el-form-item>

      <el-form-item
        :label="$t('publics.mobilePhone')"
        prop="mobile"
        class="itemBottom"
      >
        <el-input
          v-model="dataForm.mobile"
          :placeholder="$t('publics.mobilePhone')"
          maxlength="11"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('address.province')"
        prop="province"
        class="itemBottom"
      >
        <el-col :span="8">
          <el-form-item prop="province">
            <el-select
              v-model="dataForm.provinceId"
              :disabled="editAddress"
              :placeholder="$t('tip.select')"
              @change="selectProvince"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="city">
            <el-select
              v-model="dataForm.cityId"
              :disabled="editAddress"
              :placeholder="$t('tip.select')"
              @change="selectCity"
            >
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="area">
            <el-select
              v-model="dataForm.areaId"
              :disabled="editAddress"
              :placeholder="$t('tip.select')"
            >
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item
        :label="$t('address.detailed')"
        prop="addr"
      >
        <el-input
          v-model="dataForm.addr"
          :disabled="editAddress"
          :placeholder="$t('address.detailed')"
        />
      </el-form-item>
      <el-form-item v-if="isShowMap">
        <div class="map">
          <tmap
            ref="tmapRef"
            :lat-lng="latLng"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('order.cancel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="getChangeAmount()"
        >
          {{ $t('order.confirm') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { isStarMobile } from '@/utils/validate'
import { defineExpose } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
// eslint-disable-next-line no-unused-vars
const validateMobile = (rule, value, callback) => {
  if (!isStarMobile(value)) {
    callback(new Error($t('sys.mobilePhoneError')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateNotEmpty = (rule, value, callback) => {
  if (value.trim() === '') {
    callback(new Error($t('canNotBeSpace')))
  } else {
    callback()
  }
}
const emit = defineEmits(['refreshUserAddrOrder'])

const visible = ref(false)
const provinceList = ref([])
const cityList = ref([])
const areaList = ref([])
const order = ref()
const dataForm = ref({
  addrOrderId: 0,
  addrId: 0,
  addr: '',
  receiver: '',
  mobile: '',
  area: '',
  city: '',
  province: '',
  areaId: null,
  cityId: null,
  provinceId: null
})
const dataRule = reactive({
  receiver: [
    {
      required: true,
      message: $t('shop.coneeNameCanEmpty') + $t('shop.coneeNameCanEmpty'),
      trigger: 'blur'
    },
    { validator: validateNotEmpty, trigger: 'blur' }
  ],
  addr: [
    { required: true, message: $t('shop.addressCannotBeEmpty') + '', trigger: 'blur' },
    { validator: validateNotEmpty, trigger: 'blur' }
  ],
  city: [{ required: true, message: $t('shop.cityCannotBeEmpty') + '', trigger: 'blur' }],
  province: [{ required: true, message: $t('shop.provinceCannotBeEmpty') + '', trigger: 'blur' }],
  area: [{ required: true, message: $t('shop.districtCounEmpty') + '', trigger: 'blur' }],
  mobile: [
    { required: true, message: $t('sys.mobilePhoneNoNull') + '', trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ]
})
const dataListLoading = ref(false)
const isShowMap = ref(false)
const oldOrder = ref('')
const freightAmount = ref(0)
const orderStatus = ref(0)
const editAddress = ref(false)
const dataFormRef = ref(null)
const latLng = ref(null)
// 获取数据列表
const init = async isOrder => {
  const orderInfo = Object.assign({}, isOrder)
  const userAddr = orderInfo.userAddrOrder
  order.value = orderInfo
  visible.value = true
  dataListLoading.value = true
  dataForm.value = userAddr
  isShowMap.value = Boolean(orderInfo.dvyType === 4 && (orderInfo.status === 1 || orderInfo.status === 2))
  if (isShowMap.value) {
    nextTick(() => {
      latLng.value = {
        lat: dataForm.value.lat,
        lng: dataForm.value.lng
      }
    })
  }
  freightAmount.value = orderInfo.freightAmount
  orderStatus.value = orderInfo.status
  oldOrder.value = JSON.parse(JSON.stringify(orderInfo))
  editAddress.value = order.value.dvyType === 4
  listAreaByParentId().then(({ data }) => {
    provinceList.value = data
  })
  if (userAddr.provinceId && userAddr.cityId) {
    listAreaByParentId(userAddr.provinceId).then(({ data }) => {
      cityList.value = data
    })
    listAreaByParentId(userAddr.cityId).then(({ data }) => {
      areaList.value = data
    })
  }
  dataListLoading.value = false
}
const getCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}
const listAreaByParentId = pid => {
  const paramData = {}
  if (!pid) {
    paramData.level = 1
  } else {
    paramData.pid = pid
  }
  return http({
    url: http.adornUrl('/admin/area/listByPid'),
    method: 'get',
    params: http.adornParams(paramData)
  })
}
// 选择省
const selectProvince = val => {
  dataForm.value.cityId = null
  dataForm.value.city = ''
  dataForm.value.areaId = null
  dataForm.value.area = ''
  areaList.value = []
  // 获取城市的select
  const { curNode, areas } = getCurrentChild(provinceList.value, val)
  if (areas) {
    cityList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      cityList.value = data
    })
  }
}
// 选择市
const selectCity = val => {
  dataForm.value.areaId = null
  dataForm.value.area = ''
  // 获取区的select
  const { curNode, areas } = getCurrentChild(cityList.value, val)
  if (areas) {
    areaList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      areaList.value = data
    })
  }
}
const getAddr = () => {
  for (let i = 0; i < provinceList.value.length; i++) {
    if (provinceList.value[i].areaId === dataForm.value.provinceId) {
      // 将省名字保存起来
      dataForm.value.province = provinceList.value[i].areaName
    }
  }
  for (let i = 0; i < cityList.value.length; i++) {
    if (cityList.value[i].areaId === dataForm.value.cityId) {
      // 将市名字保存起来
      dataForm.value.city = cityList.value[i].areaName
    }
  }
  for (let i = 0; i < areaList.value.length; i++) {
    if (areaList.value[i].areaId === dataForm.value.areaId) {
      // 将市名字保存起来
      dataForm.value.area = areaList.value[i].areaName
    }
  }
}
const getChangeAmount = () => {
  oldOrder.value.orderId = order.value?.orderId
  oldOrder.value.orderNumber = order.value?.orderNumber
  getAddr()
  dataFormRef.value.validate(valid => {
    if (valid) {
      // 同城配送仅支持修改收件人信息不需要请求运费接口
      if (order.value?.dvyType === 4) {
        submitProds()
        return
      }
      http({
        url: http.adornUrl('/order/order/getChangeAmount'),
        method: 'get',
        params: http.adornParams({
          orderId: oldOrder.value.orderId,
          orderNumber: oldOrder.value.orderNumber,
          areaId: order.value?.userAddrOrder.areaId,
          lng: latLng.value?.lng,
          lat: latLng.value?.lat
        })
      }).then(({ data }) => {
        ElMessageBox.confirm(onChangeAmountRes(data), $t('order.tips'), {
          confirmButtonText: $t('order.confirm'),
          cancelButtonText: $t('order.cancel'),
          type: 'warning'
        }).then(() => {
          submitProds()
        })
      })
    }
  })
}

const onChangeAmountRes = (data) => {
  return (localStorage.getItem('b2cLang') === 'zh_CN' || !localStorage.getItem('b2cLang')) ? `由于地址变更，运费应${data > 0 ? '多' : '少'}收${Math.abs(data)}元，此操作不会变更订单金额，是否确认直接修改订单地址？` : `Due to the address change, the freight should be charged ${Math.abs(data)} yuan ${data > 0 ? 'more' : 'less'}. This operation will not change the order amount. Are you sure to modify the order address directly?`
}
// 确定事件
const submitProds = () => {
  getAddr()
  dataFormRef.value.validate(valid => {
    if (valid) {
      http({
        url: http.adornUrl('/order/order/changeUserAddr'),
        method: 'put',
        data: http.adornData({
          orderId: order.value.orderId,
          orderNumber: order.value.orderNumber,
          userAddrOrder: dataForm.value
        })
      }).then(data => {
        ElMessage({
          message: data.msg || data.data,
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshUserAddrOrder')
          }
        })
      })
    }
  })
}
defineExpose({ init })
</script>
<style lang="scss" scoped>
.components-order-addr-update {
  .itemBottom {
    margin-top: 10px;
    margin-bottom: 22px;
  }
  .map {
    width: 100%;
    height: 500px;
  }
}
</style>
